package wsz.demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author wsz
 * @date 2021/11/27 17:35
 **/
public class NettyClient {
    public static void main(String[] args) throws Exception {
        // 1.创建线程组
        EventLoopGroup workGroup = new NioEventLoopGroup();
        //2.创建客户端启动助手
        Bootstrap bootstrap = new Bootstrap();
        //3.设置线程组
        bootstrap.group(workGroup)
                .channel(NioSocketChannel.class) //4.设置客户端通道实现类
                .handler(new ChannelInitializer<SocketChannel>() { //5.socketchannel
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        // 添加解码器
//                        channel.pipeline().addLast("messageDecoder", new MessageDecoder());
                        // 添加编码器
//                        channel.pipeline().addLast("messageEncoder", new MessageEncoder());
                        // 编解码器
                        channel.pipeline().addLast("messageCodec", new MessageCodec());
                        // 6.向pieline中添加自定义处理
                        channel.pipeline().addLast(new ClientHandler());
                    }
                });
        // 7.启动客户端，等待连接服务端，同时将异步改为同步
        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9999);
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    System.out.println("operationComplete-数据发送成功");
                } else {
                    System.out.println("数据发送失败");
                }
            }
        });
        // 8.关闭通道和连接池
        channelFuture.channel().closeFuture().sync();
        workGroup.shutdownGracefully();
    }
}
